import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Modal } from 'antd-mobile';
import * as utils from '../../../utils'
import Numbers from '../../../components/Numbers'
export default class HorizontalProduct extends Component {
  static propTypes={
    visible:PropTypes.bool.isRequired,
    onClose:PropTypes.func.isRequired,
    onOK:PropTypes.func.isRequired,
  };
  constructor(props){
    super(props)
    /*
    val:商品数量
    skuList:将sku格式化为数组，方便展示所有属性
    selectedSkuIndex：记录当前选中的是哪个sku,
     */
    this.state={
      val:1,
      skuList:[],
      selectedSku:[],
      selectedSkuJson:{},
      selectedSkuIndex:'',
      
    }
    
  }

  onClose = key => () => {
    this.props.onClose(key)
    
  }
  componentDidMount(){
    let { data:{spec_arr}} =this.props
     this.setState({
      skuList:spec_arr,
      selectedSku:new Array(spec_arr.length)
    })
 
  }
  changeSku(pindex,cindex){
    let { skuList } =this.state 
    let { data:{goods_spec}} =this.props
    skuList.map((item,i) =>{
      if(i == pindex){
        item.checked=true
        item.spec_val.map((gitem,g) =>{
          if(g == cindex){
            gitem.checked=true
          }else{
            gitem.checked=false
          }
        })
      }
      return item
    })
    this.setState({
      skuList
    })


    let checked_num=0,spec_json={}
    //debugger
    for(let i=0;i<skuList.length;i++){
      if(!skuList[i].checked){
        break
      }else{
        checked_num++
        let selected=skuList[i].spec_val.find( item => item.checked)
        let value_json={
          [selected.spec_val_id]:selected.spec_val_name,
          name:skuList[i].spec_name
        }
        spec_json={
          ...spec_json,
          [skuList[i].spec_id]:value_json
        }
       
      }
    }
    if(checked_num === skuList.length){
      for(let i=0;i<goods_spec.length;i++){
        if(JSON.stringify( goods_spec[i].goods_spec) == JSON.stringify(spec_json)){
          this.setState({
            selectedSkuIndex:i
          })
          break
        }
      }
    }

  }
 
  _componentDidMount(){
    let { data:{goods_spec}} =this.props
    let res=[]  //最终结果
    let pids=[]  //所有属性id
    //获取sku数组
    goods_spec.map((_item,index) =>{
      let item=_item.goods_spec
      for(var i in item){
        //找出是否父属性是否相同
        let findIndex=pids.findIndex(function(value, index, arr) {
          return value == i
        })
        let jtem=item[i]
        if(findIndex == -1){
          pids=[...pids,...i]
          let presult={}  //每个属性数据
          presult.id=i
          
          let result=[]
          presult.values=result

          let a={}   //每个属性里的子属性
          for(var j in jtem){
            if(j == 'name'){
              presult.name=jtem[j]
            }else{
              a.id=j
              a.name=jtem[j]
              result.push(a)
        
            }
            
            
          }
          res.push(presult)

        }else{
          let currentLi=res.find(li =>  li.id == i)
          let a={}   //每个属性里的子属性
          for(var j in jtem){
            if(j == 'name'){
              
            }else{
              let leaf_findIndex=currentLi.values.findIndex(function(value, index, arr) {
                return value.id == j
              })
              if(leaf_findIndex > -1)  //子属性排除相同项
                break;
              a.id=j
              a.name=jtem[j]
              currentLi.values.push(a)
            }
            
            
          }

        }
        
      }
    
    })
    this.setState({
      skuList:res,
      selectedSku:new Array(res.length)
    })
 

  }

  //点击属性事件
  _changeSku(index,item,jtem){
    let {selectedSku,selectedSkuJson,skuList} =this.state
   
    let valueStr={}
    let a={[jtem.id]:jtem.name,'name':item.name}
    valueStr[item.id]=a
    selectedSkuJson={
      ...selectedSkuJson,
      [item.id]:a
    }

     //所有属性都被选择后格式化数据
    selectedSku[index]=`${item.id}_${item.name}#${jtem.id}_${jtem.name}`
    

    this.setState({
      selectedSku,
      selectedSkuJson
    },()=>{
      if(selectedSku.length ==skuList.length ){
      let hasNullIndex=selectedSku.findIndex(item => item =='' || item == undefined)
      //判断是否已经所有属性都被选择了
      if(hasNullIndex == -1){
         this.changeGoodsInfo()
      }
    }
    })

  }
  _changeGoodsInfo(){
    let { data:{goods_spec}} =this.props
    let { selectedSkuJson } =this.state

    for(let i=0;i<goods_spec.length;i++){
      if(JSON.stringify(selectedSkuJson) ==JSON.stringify(data[i].goods_spec) ){
        this.setState({
          selectedSkuIndex:i
        })
        break;
      }
    }
    
  }
  //确定事件
  onOK(){
    let { data:{goods_spec}} =this.props
    let {selectedSkuIndex,val,skuList} =this.state

    if(selectedSkuIndex === ''){
      utils.msg({text:'Please select all the attributes of the goods',code:0})
      return
    }
    let specStr=''
    skuList.map((item,i) =>{
      specStr += item.spec_name
      let child =item.spec_val.find(row => row.checked)
      specStr += `:${child.spec_val_name};`
    })

    let json={
      goods_spec_id:goods_spec[selectedSkuIndex].goods_spec_id,
      goods_num:val,
      goods_spec:this.props.type=='subGoods'?goods_spec[selectedSkuIndex].goods_spec: JSON.stringify(goods_spec[selectedSkuIndex].goods_spec),
      spec_str:specStr,
      goods_price:goods_spec[selectedSkuIndex].goods_price,
      
    }

    this.props.onOK(json)
  }
  

  render(){
    let { visible,data,isFree,goods_name} =this.props
    let {skuList,selectedSku,selectedSkuIndex } =this.state
    let {goods_spec} =data
    if(!goods_spec.length) return null
    return(
      <Modal
          popup
          visible={visible}
          onClose={this.onClose('visible')}
          animationType="slide-up"
          
        >
          <div className='goods_modal'>
          <div className='top-header' onClick={this.onClose('visible')}>
              <i className='iconfont icon-fanhui1'></i>
              <span className='text'>Select Variant</span>
            </div>
          <div className="choose-container">
            <div className='title'>
              <img src={goods_spec[selectedSkuIndex||0].spec_image||''} className='goods-img' />
              <div className='goods-details'>
                <div className='goods-name line-clamp-1'>{data.goods_name}</div>
                <div className='money'><span className='red'>${goods_spec[selectedSkuIndex||0].goods_price}</span></div>
                <div className='stock'>Stock:{goods_spec[selectedSkuIndex||0].goods_stock}</div>
              </div>
            </div>
            <div className='sku-list'>
            {
              skuList.map((item,i) =>{
                return(
                  <div className='item' key={i}>
                    <span className='sku-title'>{item.spec_name}</span>
                    <ul className='ul'>
                      {
                        item.spec_val.map((jtem,j)=>{
                          return(
                             <li  onClick={this.changeSku.bind(this,i,j)} className={jtem.checked?'li active':'li'} key={j}>{jtem.spec_val_name}{jtem.checked}
                             <b className='border_b'></b>
                             </li>
                            )
                        })   
                      }
                    </ul>
                  </div>
                  )
              })
            }
             
              
            </div>
           {/*赠品时没有选择数量*/}
            {
              isFree?null:
              <div className='selectNum'>
                <div className='l1'>Qty</div>
                <Numbers value={+this.state.val} onCallBack={(num)=>{
                                      this.setState({val:num})
                                     }} />
              </div>
            }
            
            <div className='bottom-btn-groups' >
              <span className='cancle-btn' onClick={this.onClose('visible')}>CANCEL</span>
              <span className='ok-btn' onClick={this.onOK.bind(this)}>CONTINUE</span>
            </div>
          </div>
          </div>
        </Modal>
      )
  }
 
 
} 



















